package wiki.xsx.core.snowflake.config;

import java.io.Serializable;

/**
 * 雪花
 * @author xsx
 * @date 2019/11/19
 * @since 1.8
 */
public final class Snowflake implements Serializable {

    private static final long serialVersionUID = -2282650019490872043L;

    /**
     * 当前机器码id
     */
    private long workerId;
    /**
     * 当前数据中心id
     */
    private long dataCenterId;
    /**
     * 序列
     */
    private long sequence = 0L;
    /**
     * 上一次时间戳
     */
    private long lastTimestamp = -1L;

    /**
     * 构造
     *
     * @param workerId 终端ID
     * @param dataCenterId 数据中心ID
     */
    public Snowflake(long workerId, long dataCenterId) {
        /**
         * 最大支持机器节点数0~31，一共32个
         */
        long maxWorkerId = 31L;
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(String.format("worker Id can't be greater than %s or less than 0", maxWorkerId));
        }
        /**
         * 最大支持数据中心节点数0~31，一共32个
         */
        long maxDatacenterId = 31L;
        if (dataCenterId > maxDatacenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %s or less than 0", maxDatacenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
    }

    /**
     * 获取机器id
     *
     * @return 所属机器的id
     */
    public long getWorkerId() {
        return this.workerId;
    }

    /**
     * 获取数据中心id
     *
     * @return 所属数据中心id
     */
    public long getDataCenterId() {
        return this.dataCenterId;
    }

    /**
     * 下一个ID
     *
     * @return ID
     */
    public synchronized long nextId() {
        long timestamp = genTime();
        if (timestamp < lastTimestamp) {
            // 如果服务器时间有问题(时钟后退) 报错。
            throw new IllegalStateException(String.format("Clock moved backwards. Refusing to generate id for %sms", lastTimestamp - timestamp));
        }
        if (lastTimestamp == timestamp) {
            long sequenceMask = 4095L;
            sequence = (sequence + 1) & sequenceMask;
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0L;
        }
        lastTimestamp = timestamp;
        // 2000-01-01 00：00：00
        long epoch = 946656000000L;
        return ((timestamp - epoch) << 22L) | (dataCenterId << 17L) | (workerId << 12L) | sequence;
    }

    /**
     * 下一个ID（字符串形式）
     *
     * @return ID 字符串形式
     */
    public String nextIdStr() {
        return Long.toString(nextId());
    }

    // ------------------------------------------------------------------------------------------------------------------------------------ Private method start
    /**
     * 循环等待下一个时间
     *
     * @param lastTimestamp 上次记录的时间
     * @return 下一个时间
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = genTime();
        while (timestamp <= lastTimestamp) {
            timestamp = genTime();
        }
        return timestamp;
    }

    /**
     * 生成时间戳
     *
     * @return 时间戳
     */
    private long genTime() {
        return System.currentTimeMillis();
    }
    // ------------------------------------------------------------------------------------------------------------------------------------ Private method end
}
